package com.user.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class C3P0Util {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    private static ComboPooledDataSource ds;

    static {
        //1.读取配置文件
        InputStream is = C3P0Util.class.getClassLoader().
                getResourceAsStream("ojdbc.properties");
        //2.创建处理 properties 文件对象
        Properties properties = new Properties();
        try {
            //3.properties 对象读取配置文件
            properties.load(is);
            //4.获取配置文件中指定的值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //5.创建连接池对象
            ds = new ComboPooledDataSource();

            try {
                ds.setDriverClass(driver);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            //设置连接池的初始连接数量
            ds.setInitialPoolSize(5);
            //设置最大连接数数量
            ds.setMaxPoolSize(10);
            //设置最小连接数量
            ds.setMinPoolSize(3);
            //设置使用不够时自动获取连接的数量
            ds.setAcquireIncrement(3);
            //设置两次连接的时间间隔
            ds.setAcquireRetryDelay(500);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return connection;
    }

    //关闭资源
    public static void closeAll(AutoCloseable... closeabless) {
        for (AutoCloseable closeable : closeabless) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

